<?php
namespace Hangpu888\Hpadmin\middleware;

use Hangpu888\Hpadmin\model\Admin;
use Hangpu888\Hpadmin\model\AdminLog;
use Hangpu888\Hpadmin\utils\Json;
use Hangpu888\Hpadmin\utils\manager\TokenManager;
use Shopwwi\WebmanFilesystem\Facade\Storage;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

/**
 * 后台权限控制认证中间件
 */
class Auths implements MiddlewareInterface
{
    public function process(Request $request, callable $next): Response
    {
        // 获取token
        $authorization = $request->header('Authorization');

        // 处理请求路由
        $path = substr(request()->path(), 1);
        list($module, $controller, $action) = explode('/', $path);
        $controller = ucfirst(strtolower($controller));
        $path = implode('/', [$module, $controller, $action]);

        // 白名单配置
        $adminAuths = config('plugin.hangpu888.hpadmin.whiteroute');

        // 未登录并且需要登录的路由（拦截）
        if (!in_array($path, $adminAuths) && !$authorization) {
            $request->user = new Admin;
            return Json::failFul('您未登录或已登录超时', 208);
        }
        // 白名单路由（未登录状态放行）
        if (in_array($path, $adminAuths) || !$authorization) {
            $request->user = new Admin;
            /** @var Response $response */
            $response = $next($request);
            return $response;
        }
        // 解密token
        $token = TokenManager::_decrypt_token($authorization);
        // 实例模型
        $model = new $token['model'];
        // 查询数据
        $map['id'] = $token['uid'];
        $user = $model->with(['role'])->where($map)->withoutField(['password'])->find();
        if (!$user) {
            return Json::failFul('管理员登录错误', 208);
        }
        // 检测是否已冻结
        if ($user->status == 0) {
            return Json::failFul('管理员已被冻结', 208);
        }
        // 权限检测

        // 操作日志
        $method = strtolower(request()->method());
        $ip = request()->getRealIp($safe_mode = true);
        switch ($method) {
            case "post":
                $data = request()->post();
                $logModel = new AdminLog;
                $logModel->addLog((string)$path, (string)$ip, (int)$user->id, (int)$user->role_id, 1, $data);
                break;
            case "put":
                $data = request()->post();
                $logModel = new AdminLog;
                $logModel->addLog((string)$path, (string)$ip, (int)$user->id, (int)$user->role_id, 2, $data);
                break;
            case 'delete':
                $data = request()->get();
                $logModel = new AdminLog;
                $logModel->addLog((string)$path, (string)$ip, (int)$user->id, (int)$user->role_id, 3, $data);
                break;
        }

        // 重组数据
        $user->headimg = Storage::url($user->headimg);
        $user->role_name = $user->role->title;
        $request->user = $user;

        /** @var Response $response */
        $response = $next($request);
        return $response;
    }
}
